import { ref, reactive, onMounted } from 'vue'
import { PaginationOption } from '@/config/constants'
const useTable = ({ model, modelAction = 'getList', modelData = {} }) => {
    const total = ref(0)
    const loading = ref(false)
    const list = ref([])
    const pageOption = reactive({
        pageNo: PaginationOption.PAGE,
        pageSize: PaginationOption.PAGE_SIZE
    })
    let listQuery

    const handleCurrentChange = page => {
        pageOption.pageNo = page
        getList()
    }
    const handleSizeChange = size => {
        pageOption.pageSize = size
        getList()
    }
    const handleFilter = query => {
        pageOption.pageNo = PaginationOption.PAGE
        query.reset && (pageOption.pageSize = PaginationOption.PAGE_SIZE)
        listQuery = query
        getList()
    }
    const getList = async () => {
        const data = {
            ...pageOption,
            ...modelData,
            ...listQuery
        }
        console.log(listQuery)
        try {
            loading.value = true
            const res = await model[modelAction](data)
            list.value = model.transformNull(res.list || [])
            total.value = res.totalCount
        } finally {
            loading.value = false
        }
    }
    onMounted(() => {
        getList()
    })
    return {
        pageOption,
        list,
        total,
        loading,
        getList,
        handleCurrentChange,
        handleSizeChange,
        handleFilter
    }
}

export default useTable
